from odoo import fields, models, _
from odoo.tools import float_is_zero, float_compare
from odoo.exceptions import UserError
from odoo.tools import float_compare, float_is_zero


class StockMove(models.Model):
    _inherit = 'stock.move'

    def _action_done(self, cancel_backorder=False):
        res = super()._action_done(cancel_backorder)
        parameter = self.env['ir.config_parameter'].sudo().get_param('sb_stock_inherit.s_product_quantity_lock')
        for move in self.filtered(lambda x: x.state == 'done'):
            move._purchase_requisition_change_stock()
            if parameter and move.location_dest_id.usage != 'internal':
                product_id = move.product_id
                product_rounding = product_id.uom_id.rounding
                if float_compare(product_id.qty_available, product_id.s_lock_stock_qty, precision_rounding=product_rounding) == -1:
                    raise UserError(_('Product %s, Inventory quantity is less than the locked quantity, Please contact the planner to unlock', product_id.name))

        return res

    def _purchase_requisition_change_stock(self):
        """
        采购入库时，锁在途转换为锁库存
        """
        for move in self:
            if move.state != 'done':
                continue
            if move.location_id.usage != 'supplier':
                continue
            purchase_id = move.purchase_line_id.order_id
            if not purchase_id:
                continue
            product_lock_ids = self.env['s.product.lock'].search([
                ('purchase_id', '=', purchase_id.id),
                ('product_id', '=', move.product_id.id),
                ('lock_type', '=', 'prepare')
            ])
            move_qty = move.product_uom._compute_quantity(move.quantity, move.product_id.uom_id)
            for rec in product_lock_ids:
                if float_is_zero(move_qty, precision_rounding=move.product_id.uom_id.rounding):
                    break
                result = float_compare(move_qty, rec.qty, precision_rounding=move.product_id.uom_id.rounding)
                if result == -1:
                    rec.copy({
                        'lock_type': 'stock',
                        'qty': move_qty
                    })
                    rec.write({'qty': rec.qty - move_qty})
                else:
                    rec.write({'lock_type': 'stock'})
                move_qty -= min([move_qty, rec.qty])